// 加载 CSV 文件 
d3.csv("./data/电站地理位置及资金分布.csv").then(function(data) {
  const container = d3.select('.bottom-container');
  let containerWidth = parseInt(container.style('width'));
  let containerHeight = parseInt(container.style('height'));
  
    const width = containerWidth-100;
    const height = containerHeight;
    
    // 解析日期字段（将日期字符串转为 Date 对象）
    const parseDate = d3.timeParse("%Y%m%d");
    data.forEach(d => {
        d["开工时间"] = parseDate(d["开工时间"]);
        d["并网时间"] = parseDate(d["并网时间"]);
        d["发电量"] = +d['总发电量(万千瓦时)'] || 0;  
    });

    // 提取所有日期（开工和并网时间）
    const allDates = data.reduce((acc, d) => {
        acc.push(d["开工时间"]);
        acc.push(d["并网时间"]);
        return acc;
    }, []);
    
    // 时间比例尺
    const xLineScale = d3.scaleTime()
      .domain([d3.min(allDates), d3.max(allDates)])
      .range([25, width]);

    // Y轴比例尺（电站数量）
    const yLineScale = d3.scaleLinear()
      .domain([0, data.length]) // Y轴的范围为电站数量的最大值
      .range([height, 50]);

    // Y轴比例尺（总发电量）  
    const yScale2 = d3.scaleLinear()
      .domain([0, 40]) // Y轴的范围为电站数量的最大值
      .range([height, 50]);

    // 计算每个日期的开工和并网电站数量
    const counts = [];
    const dates = Array.from(new Set(allDates)).sort((a, b) => a - b);

    dates.forEach(date => {
        let countOpen = 0;
        let countGrid = 0;
        let totalPower = 0;

        data.forEach(d => {
            if (d["开工时间"] <= date) countOpen++;
            if (d["并网时间"] <= date) countGrid++;
            if (d["并网时间"] <= date) totalPower += d["发电量"];
        });

        counts.push({
            date: date,
            countOpen: countOpen,
            countGrid: countGrid,
            totalPower: totalPower
        });
    });

    // 折线生成器
    const lineOpen = d3.line()
      .x(d => xLineScale(d.date))
      .y(d => yLineScale(d.countOpen));

    const lineGrid = d3.line()
      .x(d => xLineScale(d.date))
      .y(d => yLineScale(d.countGrid));

    const linePower = d3.line()
      .x(d => xLineScale(d.date))
      .y(d => yScale2(d.totalPower));

    // 创建SVG元素
    const linesvg = d3.select("#line-svg").attr('width', width +200 )
      .attr('height', height + 50);

    // 绘制X轴（时间轴）
    linesvg.append("g")
      .attr("class", "axis")
      .attr("transform", `translate(0, ${height})`)  // X轴位置
      .call(d3.axisBottom(xLineScale).ticks(d3.timeMonth.every(1)))
      .selectAll("text")
      .style("text-anchor", "middle");

    // 绘制Y轴（数量轴）
    linesvg.append("g")
      .attr("class", "axis")
      .attr("transform", "translate(25, 0)")  // Y轴位置
      .call(d3.axisLeft(yLineScale));

    // 绘制Y2轴（数量轴）
    linesvg.append("g")
      .attr("class", "axis")
      .attr("transform", `translate(${width}, 0)`)  // Y轴位置
      .call(d3.axisRight(yScale2));

    // 在Y轴上方添加文本标注单位 
    linesvg.append("text")
      .attr("x", 50)  // X坐标，使其对齐到Y轴位置
      .attr("y", 40)  // Y坐标，将文本放置在Y轴上方
      .attr("text-anchor", "middle")  // 文本水平居中
      .text("电站数量(个)")
      .style("font-size", "14px");
    
    linesvg.append("text")
      .attr("x", width)  // X坐标，使其对齐到Y轴位置
      .attr("y", 40)  // Y坐标，将文本放置在Y轴上方
      .attr("text-anchor", "middle")  // 文本水平居中
      .text("总发电量(万千瓦时)")
      .style("font-size", "14px");

    // 绘制开工电站数量折线
    const lineOpenPath = linesvg.append("path")
      .data([counts])
      .attr("class", "line")
      .attr("d", lineOpen)
      .attr("fill", "none")
      .attr("stroke", "blue")
      .attr("stroke-width", 2);

    // 绘制并网电站数量折线
    const lineGridPath = linesvg.append("path")
      .data([counts])
      .attr("fill", "none")
      .attr("class", "line")
      .attr("d", lineGrid)
      .attr("stroke", "green")
      .attr("stroke-width", 2);

    // 绘制总发电量折线（河流图）
    const linePowerPath = linesvg.append("path")
      .data([counts])
      .attr("class", "line")
      .attr("d", linePower)
      .attr("fill", "none")
      .attr("stroke", "orange")
      .attr("stroke-width", 2);

    // 设置路径动画
    function drawLine(path) {
        const length = path.node().getTotalLength();
        path.attr("stroke-dasharray", length)
            .attr("stroke-dashoffset", length)
            .transition()
            .duration(2000)  // 设置动画时长
            .ease(d3.easeLinear)
            .attr("stroke-dashoffset", 0);
    }

    // 调用动画
    drawLine(lineOpenPath);
    drawLine(lineGridPath);
    drawLine(linePowerPath);

    // 添加图例
    const linelegend = linesvg.append("g")
      .attr("transform", `translate(100, 50)`);

    linelegend.append("rect")
      .attr("width", 18)
      .attr("height", 18)
      .attr("fill", "blue");

    linelegend.append("text")
      .attr("x", 24)
      .attr("y", 9)
      .attr("dy", "0.35em")
      .text("开工电站")
      .style("font-size", "12px");

    linelegend.append("rect")
      .attr("width", 18)
      .attr("height", 18)
      .attr("fill", "green")
      .attr("y", 20);

    linelegend.append("text")
      .attr("x", 24)
      .attr("y", 29)
      .attr("dy", ".35em")
      .text("并网电站")
      .style("font-size", "12px");

    // 添加总发电量的图例
    linelegend.append("rect")
        .attr("width", 18)
        .attr("height", 18)
        .attr("fill", "orange")
        .attr("y", 40);

    linelegend.append("text")
        .attr("x", 24)
        .attr("y", 49)
        .attr("dy", ".35em")
        .text("总发电量")
        .style("font-size", "12px");

    // 监听窗口变化，调整SVG尺寸
window.addEventListener("resize", resizeSVG);

function resizeSVG() {
    containerWidth = parseInt(container.style('width'));
    containerHeight = parseInt(container.style('height'));
    
    const width = containerWidth - 100;
    const height = containerHeight;

    // 更新SVG大小
    linesvg.attr('width', width + 200).attr('height', height + 50);

    // 更新比例尺范围
    xLineScale.range([25, width]);
    yLineScale.range([height, 50]);
    yScale2.range([height, 50]);

    // 更新X轴
    linesvg.select(".axis.x")
        .attr("transform", `translate(0, ${height})`)
        .call(d3.axisBottom(xLineScale).ticks(d3.timeMonth.every(1)));

    // 更新Y轴
    linesvg.select(".axis.y-left")
        .call(d3.axisLeft(yLineScale));

    linesvg.select(".axis.y-right")
        .attr("transform", `translate(${width}, 0)`)
        .call(d3.axisRight(yScale2));

    // 更新折线
    lineOpenPath.attr("d", lineOpen);
    lineGridPath.attr("d", lineGrid);
    linePowerPath.attr("d", linePower);
}

}).catch(function(error) {
    console.error('Error loading the CSV data: ', error);
});
